//
//  QianliAppearView.swift
//  todoios
//
//  Created by qianli on 2025/4/10.
//

import UIKit
import SwiftyUserDefaults

class QianliAppearView: UIView {

    private var IB5he4Yk80F28O9P:UIProgressView?
    var tapBlock: os_block_t?
    var _progressBar: QianliAppearProgressView?
    private var IglOrA3ytA044k05: CADisplayLink?
    private var OvcJWryLhuChvRP8: CGFloat = 0.0
    private var bCmqB4N3u4LNsW01:Bool = false
    deinit {
        QianliUniversalFunc.QianliLog("------QianliAppearView.deinit")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.GHL4Rhb91XYBer27()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func GHL4Rhb91XYBer27(){
        self.backgroundColor = .systemBackground
//添加logo
        let iLeft = qianli_pm_width/2 - 120/2
        let adImgView = UIImageView(frame: CGRect(x: iLeft, y: qianli_pm_height - 144*2.5, width: 120, height: 120))
        adImgView.isUserInteractionEnabled = false
        adImgView.contentMode = .scaleAspectFill
        adImgView.clipsToBounds = true
        adImgView.qianli_assets("qianli_logo_main")
        self.addSubview(adImgView)
        
//添加自定义进度条
        // 添加进度条
        self.IB5he4Yk80F28O9P = UIProgressView(progressViewStyle: .default)
        if let progressview = self.IB5he4Yk80F28O9P{
            // 设置进度条的位置和大小，这里简单地将其放在 adImageView 下方
            progressview.frame = CGRect(x: 30, y: adImgView.frame.maxY + 50, width: qianli_pm_width-60, height: 10)
            progressview.progress = 0
            progressview.tintColor = .blue.withAlphaComponent(0.5)
            self.addSubview(progressview)
            progressview.isHidden = true
        }
        
        if Defaults[\.isFirster] {
            //显示3张引导页
            let scrollview = UIScrollView(frame: CGRect(x: 0, y: 0, width: qianli_pm_width, height: qianli_pm_height))
            self.addSubview(scrollview)
            let img_1 = UIImageView(frame: CGRect(x: 0, y: 0, width: qianli_pm_width, height: qianli_pm_height))
            scrollview.addSubview(img_1)
            img_1.image = "qianli_guide_1".qianli_R_image
            
            let img_2 = UIImageView(frame: CGRect(x: qianli_pm_width, y: 0, width: qianli_pm_width, height: qianli_pm_height))
            scrollview.addSubview(img_2)
            img_2.image = "qianli_guide_2".qianli_R_image
            
            let img_3 = UIImageView(frame: CGRect(x: qianli_pm_width*2, y: 0, width: qianli_pm_width, height: qianli_pm_height))
            scrollview.addSubview(img_3)
            img_3.image = "qianli_guide_3".qianli_R_image
            img_3.isUserInteractionEnabled = true
            
            let iBottomSpace = UIDevice.qianli_Height_Sacle_Unit(204.0)
            let btn = GradientBtn(frame: CGRect(x: qianli_pm_width/2-240/2, y: qianli_pm_height-iBottomSpace, width: 240, height: 48), title: LocalizedString("Enjoy Now"))
            img_3.addSubview(btn)
            btn.touch_With_Block {[weak self] sender in
                Defaults[\.isFirster] = false
                self?.PDAk8rZnPGx0LtFo()
            }
            scrollview.isPagingEnabled = true
            scrollview.contentSize = CGSize(width: qianli_pm_width*3, height: qianli_pm_height)
            
            //超出边界不能滚动，以免露出后面的view来
            scrollview.bounces = false
            scrollview.alwaysBounceHorizontal = false
            
            //右上角跳过
            let topSpace = UIDevice.qianli_statusbar_and_navibar_height()
            let passBtn = UIButton(frame: CGRect(x: qianli_pm_width-15-60, y: topSpace-40, width: 54, height: 28))
            passBtn.setTitle("跳过", for: .normal)
            passBtn.setTitleColor(.black, for: .normal)
            passBtn.titleLabel?.font = .systemFont(ofSize: 13)
            passBtn.layer.borderColor = UIColor.gray.cgColor
            passBtn.layer.borderWidth = 0.5
            passBtn.layer.cornerRadius = 14
            self.addSubview(passBtn)
            passBtn.touch_With_Block {[weak self] sender in
                Defaults[\.isFirster] = false
                self?.k8dNqhAW2hFcPPDM()
            }
        }else{
            NiU3nt0lBgNR4P9D(adImgView.frame.maxY + 50)
        }
        self.perform(#selector(X2oMsW06aoTaFTGs), with: nil, afterDelay: 2.0)
        //防止动画失败，无法触发readyBlock,所以稍大一点，大于1s
        
        if !Defaults[\.isFirster]{
            self.perform(#selector(PDAk8rZnPGx0LtFo), with: nil, afterDelay: 5.0) //超时显示到主页面
        }
    }
    
    private func NiU3nt0lBgNR4P9D(_ yPos:CGFloat){
        self._progressBar = QianliAppearProgressView(frame: CGRect(x: 30, y: yPos, width: qianli_pm_width-60, height: 60))
        if let _progressbar = self._progressBar{
            self.addSubview(_progressbar)
            _progressbar.backgroundColor = .systemBackground
            _progressbar.S9RnAOPK9bshC6dc()
            _progressbar.readyBlock = {[weak self] isReady in
                if isReady{
                    
                    self?.rJ4dsD4Hrk3RWtpI()
                }
            }
            _progressbar.completeBlock = { [weak self]isDone in
                if isDone{
                    
                    self?.aDQjooaSGAappzS2()
                }
            }
        }
    }
    
    private func aDQjooaSGAappzS2(){
        
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(k8dNqhAW2hFcPPDM), object: nil)
        NSObject.cancelPreviousPerformRequests(withTarget: self)
        self.perform(#selector(PDAk8rZnPGx0LtFo), with: nil, afterDelay: 1.0)
    }
    
    @objc private func X2oMsW06aoTaFTGs(){
        
        self.rJ4dsD4Hrk3RWtpI()
    }
    
    private func rJ4dsD4Hrk3RWtpI(){
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(X2oMsW06aoTaFTGs), object: nil)

        self.sgo5QSdKoAy4nRt9()
        let tapGes = UITapGestureRecognizer(target: self, action: #selector(PDAk8rZnPGx0LtFo))
        self.addGestureRecognizer(tapGes)
        
        if !LoginViewModel.shared.isDarwined && !isGetting{
            isGetting = true
            LoginViewModel.shared.url_JKou_Index = Defaults[\.lastJKouUrlIndex]
            if LoginViewModel.shared.url_JKou_Index >= 0 && LoginViewModel.shared.url_JKou_Index < QianliConfig.SERVIER_URL.count{
                LoginViewModel.shared.url_JKou = QianliConfig.SERVIER_URL[LoginViewModel.shared.url_JKou_Index]
            }else{
                LoginViewModel.shared.url_JKou_Index = 0
                LoginViewModel.shared.url_JKou = QianliConfig.SERVIER_URL[0]
                Defaults[\.lastJKouUrlIndex] = 0
            }
            print("-----handleQianliAppearPublicSetting>[\(LoginViewModel.shared.url_JKou_Index)]\(LoginViewModel.shared.url_JKou)")
            LoginViewModel.shared.getPulicSetting { result in
                DispatchQueue.main.async {[weak self] in
                    self?.Qq4xrrqTp8SguXGO()
                }
            } //每次启动都重新获取最新参数
        }else{
            print("-----cancel>isGetting:\(isGetting)")
        }
    }
    
    private func Qq4xrrqTp8SguXGO(){
        self.perform(#selector(k8dNqhAW2hFcPPDM), with: nil, afterDelay: 1.5)
    }
    
    @objc private func k8dNqhAW2hFcPPDM(){
        if let prolink = self.IglOrA3ytA044k05{
            prolink.invalidate()
        }
        self.IglOrA3ytA044k05 = nil
        
        if let progressBar = self.IB5he4Yk80F28O9P{
            progressBar.setProgress(1.0, animated: true)
            self._progressBar?.progress = 1.0
        }
        
        NSObject.cancelPreviousPerformRequests(withTarget: self)
        
        self.perform(#selector(PDAk8rZnPGx0LtFo), with: nil, afterDelay: 1.0)
    }
    
    @objc func lrKbztwSKYl94g8L() {
        // 每帧增长的进度（根据总时长调整，这里假设2秒完成）
        let increment: CGFloat = 0.005 // 60fps * 2秒 = 120帧，每帧增长1/120
        self.OvcJWryLhuChvRP8 += increment
        
        if self.OvcJWryLhuChvRP8 >= 1.0 {
            
            self.OvcJWryLhuChvRP8 = 1.0
            progressUpdateLink?.invalidate()
            progressUpdateLink = nil
            
        }
        
        // 更新进度（会触发indicator移动）
        self._progressBar?.progress = self.OvcJWryLhuChvRP8
        if let progressBar = self.IB5he4Yk80F28O9P{
            progressBar.setProgress(Float(self.OvcJWryLhuChvRP8), animated: true)
        }
    }
    
    private func sgo5QSdKoAy4nRt9(){
        if self.IglOrA3ytA044k05 == nil{
            
            self.IglOrA3ytA044k05 = CADisplayLink(target: self, selector: #selector(lrKbztwSKYl94g8L))
            if let progressLink = self.IglOrA3ytA044k05{
                if #available(iOS 15.0, *) { // 适配高刷新率屏幕（iOS 15+）
                    progressLink.preferredFrameRateRange = CAFrameRateRange(minimum: 30, maximum: 120, preferred: 60)
                }
                progressLink.add(to: .current, forMode: .common)
            }
        }else{
            print("-----cancel>exist:progressUpdateLink")
        }
        
//            let timer = Timer.scheduledTimer(withTimeInterval: 1.0/60.0, repeats: true) { [weak self] timer in
//                currentProgress += 0.001
//                if currentProgress >= 1.0 {
//                    currentProgress = 1.0
//                    timer.invalidate()
//                    self?.k8dNqhAW2hFcPPDM()
//                }
//                self?._progressBar?.progress = currentProgress
//                progressBar.setProgress(Float(currentProgress), animated: true)
//            }
//            timer.fire()
     
    }
    
    @objc func PDAk8rZnPGx0LtFo(){
        if !Defaults[\.isFirster]{
            self.IglOrA3ytA044k05?.invalidate()
            self.IglOrA3ytA044k05 = nil
            NSObject.cancelPreviousPerformRequests(withTarget: self)
            self.tapBlock?()
        }
    }
    
    func rJBNSJSqnQMvphPf(){
//UIApplication.shared.keyWindow?.addSubview(self)
        
//'keyWindow' was deprecated in iOS 13.0,改为:
//        UIApplication.shared.windows.filter{$0.isKeyWindow}.first?.addSubview(self)
//        UIApplication.shared.windows 15.0后已弃用
        let scene = UIApplication.shared.connectedScenes.first
        guard let windowScene = scene as? UIWindowScene else  {return}
        if let window = windowScene.windows.filter({$0.isKeyWindow}).first{
            window.addSubview(self)
        }
//或：
//UIApplication.shared.windows.first { $0.isKeyWindow }?.addSubview(self)
        
    }

}

